/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.jasonchoi.gatewayzuul.swagger;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;


@Component
@Primary
public class SwaggerResourceConfig implements SwaggerResourcesProvider {

    Logger logger= LoggerFactory.getLogger(SwaggerResourceConfig.class);


    @Autowired
    RouteLocator routeLocator;

    @Autowired
    private Environment environment;

    @Override
    public List<SwaggerResource> get() {
        //获取所有router
        List<SwaggerResource> resources = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        logger.info("Route Size:{}", routes.size());
        for (Route route : routes) {
            String serviceId = route.getId();
            resources.add(swaggerResource(serviceId + "所有接口", route.getFullPath().replace("**", "v2/api-docs")));
            String property = environment.getProperty(String.format("zuul.routes.%s.swagger-groupname", serviceId));
            if (StringUtils.isNotBlank(property)) {
                //在这里处理分组的swagger，可以通过配置文件的方式配置需要分组的微服务，然后单独处理
                String[] groupNames = property.split(",");
                for (String groupName : groupNames) {
                    String location = route.getFullPath().replace("**", "v2/api-docs?group=" + groupName);
                    resources.add(swaggerResource(String.format("%s__%s", serviceId, groupName), location));
                }
            }
        }
        return resources;
    }
    private SwaggerResource swaggerResource(String name, String location) {
        logger.info("name:{},location:{}",name,location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}
